package com.lz.gmall.payment.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lz.gamll.feign.order.OrderFeignClient;
import com.lz.gmall.order.entity.OrderInfo;
import com.lz.gmall.payment.properties.AliPayProperties;
import com.lz.gmall.payment.service.PaymentService;
import com.lz.gmall.rabbit.constant.RabbitConstant;
import io.swagger.annotations.Api;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 郭运龙
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AliPayProperties aliPayProperties;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public String payment(String orderId) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayProperties.getServerUrl(),
                aliPayProperties.getAppId(),
                aliPayProperties.getPrivateKey(),
                aliPayProperties.getFormat(),
                aliPayProperties.getCharset(),
                aliPayProperties.getPublicKey(),
                aliPayProperties.getSignType());

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(aliPayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(aliPayProperties.getNotifyUrl());

        OrderInfo orderInfo = orderFeignClient.getPayOrder(orderId).getData();
        Map<String, Object> params =new HashMap<>();
        params.put("out_trade_no",orderInfo.getOutTradeNo());
        params.put("total_amount",orderInfo.getTotalAmount());
        params.put("subject",orderInfo.getTradeBody());
        params.put("product_code","FAST_INSTANT_TRADE_PAY");

        //设置支付的过期时间
        Date expireTime = orderInfo.getExpireTime();
        String format = DateUtil.format(expireTime, "yyyy-MM-dd HH:mm:ss");
        params.put("time_expire",format);
        String bizContent = JSON.toJSONString(params);

        alipayRequest.setBizContent(bizContent);

        //请求
        try {
            return alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 支付成功自动异步调用该方法,通过rabbit更改订单的状态
     * @param params 支付宝支付成功之后，回调该方法
     * @return
     */
    @Override
    public String listenpayed(Map<String, String> params) {

        try {
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params,
                    aliPayProperties.getPublicKey(),
                    aliPayProperties.getCharset(),
                    aliPayProperties.getSignType());
            if (signVerified){
                String paramsStr = JSON.toJSONString(params);
                //通过rabbitmq发送消息，异步调用
                rabbitTemplate.convertAndSend(RabbitConstant.ORDER_EXCHANGE_NAME,RabbitConstant.PAYED_QUEUE_ROUTING_KEY_NAME,paramsStr);
                return "success";
            }else {
                return "error";
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
